﻿namespace Atomic.Plugins.Security.Controllers
{
    using System.Web.Mvc;

    using Atomic.Mvc.Settings;
    using Atomic.Mvc.Filters;
    using Atomic.Core.Security;
    using Atomic.Plugins.Security.Application;
    using Atomic.Plugins.Security.Domain;

    /// <summary>
    /// 账户控制器。
    /// </summary>
    [Layout]
    public class AccountController : Controller
    {
        /// <summary>
        /// 站点信息。
        /// </summary>
        private readonly ISite _site = null;

        /// <summary>
        /// 账户应用服务。
        /// </summary>
        private readonly IAccountAppService _accountAppService = null;

        /// <summary>
        /// 初始化账户控制器。
        /// </summary>
        /// <param name="accountAppService">账户应用服务。</param>
        public AccountController(IAccountAppService accountAppService)
        {
            this._site = SiteFactory.Current;
            this._accountAppService = accountAppService;
        }

        #region 用户登录

        /// <summary>
        /// 登录。
        /// </summary>
        /// <returns></returns>
        [AtomicAuthorize(Permissions.User_SignIn)]
        public ActionResult Login()
        {
            if (this.Request.IsAuthenticated)
            {
                return this.Redirect(this._site.HomePage);
            }

            return View();
        }

        /// <summary>
        /// 登录。
        /// </summary>
        /// <param name="loginUserModel">登录信息。</param>
        /// <returns></returns>
        [AtomicAuthorize(Permissions.User_SignIn)]
        [HttpPost]
        public ActionResult Login(LoginUserModel loginUserModel)
        {
            if (this.ModelState.IsValid)
            {
                var status = this._accountAppService.Login(loginUserModel.AccountNumber, loginUserModel.Password);

                if (LoginUserStatus.Success == status)
                {
                    return this.Redirect(this._site.HomePage);
                }
                else
                {
                    switch (status)
                    {
                        case LoginUserStatus.UserInvalid:
                            this.ModelState.AddModelError("AccountNumber", "该用户不存在。");
                            break;
                        case LoginUserStatus.Error:
                            this.ModelState.AddModelError("Password", "密码错误。");
                            break;
                    }
                }
            }

            return View(loginUserModel);
        }

        #endregion

        #region 用户注销

        /// <summary>
        /// 用户注销。
        /// </summary>
        /// <returns></returns>
        [Login]
        public ActionResult LogOff(string returnUrl)
        {
            this._accountAppService.Logout();

            if (!string.IsNullOrWhiteSpace(returnUrl))
            {
                return this.Redirect(returnUrl);
            }

            return this.Redirect(this._site.HomePage);
        }

        #endregion
    }
}